<template>
  <div class="min-h-screen bg-blue-50">
    <!-- 页面头部 -->
    <header class="border-b border-gray-200 relative overflow-hidden py-8 sm:py-12 lg:py-16">
      <!-- 弹幕系统 -->
      <BarrageSystem 
        :stats-data="{
          total: totalCount,
          solved: favoritesCount,
          rate: 85.6,
          submissions: todayNewCount
        }"
        :custom-barrage-data="resourceBarrageData"
        @tag-click="handleTagClick"
      />

      <!-- 主要内容层 -->
      <div class="container mx-auto px-4 py-4 sm:py-6 lg:py-8 relative z-10">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-gradient-to-r from-purple-600 to-indigo-600 rounded-full mb-3 sm:mb-4 shadow-lg">
            <svg class="w-6 h-6 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
            </svg>
          </div>
          <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-purple-700 via-indigo-600 to-blue-600 bg-clip-text text-transparent">学习资源</h1>
          <p class="text-gray-600 mt-2 text-base sm:text-lg">丰富的学习资料和资源库，助你提升技能</p>
        </div>
      </div>
    </header>

    <!-- 统计信息和快捷操作 -->
    <div class="container mx-auto px-4 py-4">
      <div class="bg-white/90 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 p-4 mb-4">
        <!-- 统计信息和快捷操作按钮在同一行 -->
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <!-- 统计信息 -->
          <div class="flex flex-wrap gap-2 sm:gap-4 w-full sm:w-auto">
            <div class="group bg-gradient-to-r from-blue-100 to-blue-200 text-blue-800 rounded-full px-4 py-2 shadow-sm">
              <span class="font-medium">资源总数</span>
              <span class="ml-2 font-bold text-lg">{{ totalCount }}</span>
            </div>
            <div class="group bg-gradient-to-r from-yellow-500 to-orange-500 text-white rounded-full px-4 py-2 shadow-sm">
              <span class="font-medium">我的收藏</span>
              <span class="ml-2 font-bold text-lg">{{ favoritesCount }}</span>
            </div>
            <div class="group bg-gradient-to-r from-purple-100 to-purple-200 text-purple-800 rounded-full px-4 py-2 shadow-sm">
              <span class="font-medium">今日新增</span>
              <span class="ml-2 font-bold text-lg">{{ todayNewCount }}</span>
            </div>
          </div>

          <!-- 快捷操作按钮 -->
          <div class="flex flex-wrap gap-3">
            <button 
              @click="navigateToSubmitResource"
              class="group flex items-center px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-lg hover:from-blue-600 hover:to-indigo-600 transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105 text-sm"
            >
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
              提交资源
            </button>
            <button class="group flex items-center px-4 py-2 bg-gradient-to-r from-yellow-500 to-orange-500 text-white rounded-lg hover:from-yellow-600 hover:to-orange-600 transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105 text-sm">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path>
              </svg>
              我的收藏
            </button>
            <button class="group flex items-center px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg hover:from-purple-600 hover:to-pink-600 transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-105 text-sm">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-5 5-5-5h5v-5a7.5 7.5 0 00-15 0v5h5l-5 5-5-5h5v-5a7.5 7.5 0 0115 0v5z"></path>
              </svg>
              订阅更新
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-4">
      <!-- 移除左侧栏后，主内容全宽展示 -->
      <section class="space-y-4">
      <!-- 分类导航 -->
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 p-4 mb-4">
        <div class="flex flex-wrap gap-3">
          <button
            v-for="category in categories"
            :key="category.id"
            :class="[
              'px-6 py-3 rounded-xl font-medium transition-all duration-200 transform hover:scale-105',
              selectedCategory === category.id
                ? 'bg-gradient-to-r from-blue-600 to-purple-600 text-white shadow-lg'
                : 'bg-white/80 backdrop-blur-sm text-gray-700 hover:bg-gray-50 hover:shadow-md border border-gray-200/50'
            ]"
            @click="selectedCategory = category.id"
          >
            {{ category.name }}
          </button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 p-4 mb-4">
        <div class="flex flex-col md:flex-row gap-4">
          <div class="flex-1">
            <div class="relative">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索资源..."
                class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm transition-all duration-200"
              />
              <svg class="absolute left-4 top-3.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>
          <div class="flex gap-3">
            <div class="relative w-48">
              <button
                type="button"
                class="w-full px-6 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm hover:bg-gray-50 hover:shadow-md transition-all duration-200 text-left"
                @click="difficultyOpen = !difficultyOpen"
              >
                {{ difficultyLabel }}
                <span class="float-right text-gray-400">▼</span>
              </button>
              <ul
                v-if="difficultyOpen"
                class="absolute z-10 mt-2 w-full bg-white rounded-xl border border-gray-200 shadow-lg overflow-hidden"
              >
                <li
                  v-for="opt in difficultyOptions"
                  :key="opt.value"
                  class="px-4 py-2 cursor-pointer hover:bg-blue-500 hover:text-white"
                  @click="selectedDifficulty = opt.value; difficultyOpen = false"
                >
                  {{ opt.label }}
                </li>
              </ul>
            </div>
            <div class="relative w-40">
              <button
                type="button"
                class="w-full px-6 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm hover:bg-gray-50 hover:shadow-md transition-all duration-200 text-left"
                @click="sortOpen = !sortOpen"
              >
                {{ sortLabel }}
                <span class="float-right text-gray-400">▼</span>
              </button>
              <ul
                v-if="sortOpen"
                class="absolute z-10 mt-2 w-full bg-white rounded-xl border border-gray-200 shadow-lg overflow-hidden"
              >
                <li
                  v-for="opt in sortOptions"
                  :key="opt.value"
                  class="px-4 py-2 cursor-pointer hover:bg-blue-500 hover:text-white"
                  @click="selectedSort = opt.value; sortOpen = false"
                >
                  {{ opt.label }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="text-center py-12">
        <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-4">
          <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-500 mb-4">{{ error }}</p>
        <button 
          @click="loadResources"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          重试
        </button>
      </div>

      <!-- 资源列表 -->
      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div
          v-for="resource in filteredResources"
          :key="resource.id"
          class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 overflow-hidden hover:shadow-xl transition-all duration-300 transform hover:scale-105 cursor-pointer group"
          @click="viewResource(resource)"
        >
          <!-- 资源封面 -->
          <div class="relative h-56 bg-gradient-to-br from-blue-500 to-purple-600 overflow-hidden">
            <img
              v-if="resource.thumbnail_url"
              :src="resource.thumbnail_url"
              :alt="resource.title"
              class="absolute inset-0 w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
            />
            <div
              v-if="resource.video_url"
              class="absolute inset-0 bg-black/30 flex items-center justify-center group-hover:bg-black/40 transition-colors duration-300"
            >
              <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center group-hover:bg-white/30 transition-colors duration-300">
                <svg class="w-8 h-8 text-white ml-1" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M8 5v14l11-7z"/>
                </svg>
              </div>
            </div>
            <div v-else class="w-full h-full flex items-center justify-center">
              <div class="text-white text-center">
                <svg class="w-16 h-16 mx-auto mb-3 group-hover:scale-110 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                </svg>
                <span class="text-sm font-medium">{{ getResourceTypeName(resource.type) }}</span>
              </div>
            </div>
            
            <!-- 资源类型标签 -->
            <div class="absolute top-4 left-4">
              <span
                :class="[
                  'px-3 py-1.5 rounded-full text-xs font-semibold shadow-lg backdrop-blur-sm',
                  resource.type === 'course' ? 'bg-blue-500/90 text-white' :
                  resource.type === 'project' ? 'bg-green-500/90 text-white' :
                  resource.type === 'book' ? 'bg-purple-500/90 text-white' :
                  'bg-gray-500/90 text-white'
                ]"
              >
                {{ getResourceTypeName(resource.type) }}
              </span>
            </div>

            <!-- 难度标签 -->
            <div class="absolute top-4 right-4">
              <span
                :class="[
                  'px-3 py-1.5 rounded-full text-xs font-semibold shadow-lg backdrop-blur-sm',
                  resource.difficulty === 'beginner' ? 'bg-green-500/90 text-white' :
                  resource.difficulty === 'medium' ? 'bg-yellow-500/90 text-white' :
                  'bg-red-500/90 text-white'
                ]"
              >
                {{ getDifficultyName(resource.difficulty) }}
              </span>
            </div>
          </div>

          <!-- 资源信息 -->
          <div class="p-6">
            <h3 class="text-xl font-bold text-gray-900 mb-3 line-clamp-2 group-hover:text-blue-600 transition-colors duration-200">{{ resource.title }}</h3>
            <p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ resource.description }}</p>

            <!-- 作者和统计信息 -->
            <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
              <div class="flex items-center space-x-2">
                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                </svg>
                <span class="font-medium">{{ resource.author }}</span>
              </div>
              <div class="flex items-center space-x-4">
                <span class="flex items-center text-gray-500 hover:text-blue-600 transition-colors duration-200">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                  {{ resource.views }}
                </span>
                <span class="flex items-center text-gray-500 hover:text-red-500 transition-colors duration-200">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                  </svg>
                  {{ resource.likes }}
                </span>
              </div>
            </div>

            <!-- 特殊信息显示 -->
            <div v-if="resource.type === 'course'" class="mb-4">
              <div class="flex items-center justify-between text-sm">
                <span v-if="resource.duration" class="text-gray-600">
                  时长: {{ formatDuration(resource.duration) }}
                </span>
                <span v-if="resource.rating" class="flex items-center text-yellow-600">
                  <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                  </svg>
                  {{ resource.rating.toFixed(1) }} ({{ resource.rating_count }})
                </span>
              </div>
            </div>

            <div v-if="resource.type === 'project'" class="mb-4">
              <div v-if="resource.tech_stack" class="flex flex-wrap gap-1">
                <span
                  v-for="tech in resource.tech_stack.slice(0, 3)"
                  :key="tech"
                  class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                >
                  {{ tech }}
                </span>
                <span
                  v-if="resource.tech_stack.length > 3"
                  class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full"
                >
                  +{{ resource.tech_stack.length - 3 }}
                </span>
              </div>
            </div>

            <div v-if="resource.type === 'book'" class="mb-4">
              <div class="flex items-center justify-between text-sm text-gray-600">
                <span v-if="resource.pages">页数: {{ resource.pages }}</span>
                <span v-if="resource.format">{{ resource.format }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex items-center justify-between">
              <button
                class="flex items-center space-x-2 text-gray-600 hover:text-red-500 text-sm font-medium transition-colors duration-200"
                @click.stop="toggleFavorite(resource)"
              >
                <svg class="w-4 h-4" :class="resource.is_favorited ? 'fill-current' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                </svg>
                <span>{{ resource.is_favorited ? '已收藏' : '收藏' }}</span>
              </button>
              <div class="flex space-x-2">
                <button
                  v-if="resource.type === 'course'"
                  class="px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl text-sm font-medium hover:from-blue-700 hover:to-blue-800 transition-all duration-200 transform hover:scale-105 shadow-lg"
                  @click.stop="enrollCourse(resource)"
                >
                  {{ resource.is_enrolled ? '继续学习' : '开始学习' }}
                </button>
                <button
                  v-else-if="resource.type === 'book'"
                  class="px-4 py-2 bg-gradient-to-r from-purple-600 to-purple-700 text-white rounded-xl text-sm font-medium hover:from-purple-700 hover:to-purple-800 transition-all duration-200 transform hover:scale-105 shadow-lg"
                  @click.stop="downloadBook(resource)"
                >
                  下载
                </button>
                <button
                  class="px-4 py-2 bg-gradient-to-r from-gray-600 to-gray-700 text-white rounded-xl text-sm font-medium hover:from-gray-700 hover:to-gray-800 transition-all duration-200 transform hover:scale-105 shadow-lg"
                  @click.stop="viewResource(resource)"
                >
                  查看详情
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 - 大比例显示 -->
      <div v-if="!loading && !error && filteredResources.length === 0" class="min-h-[60vh] flex items-center justify-center bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50">
        <div class="text-center max-w-2xl mx-auto px-8 py-16">
          <div class="w-32 h-32 bg-gradient-to-br from-blue-100 to-purple-100 rounded-full flex items-center justify-center mx-auto mb-8">
            <svg class="w-16 h-16 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
            </svg>
          </div>
          <h3 class="text-4xl font-bold text-gray-900 mb-6">暂无资源</h3>
          <p class="text-gray-600 mb-10 text-xl leading-relaxed">该分类下暂时没有学习资源，请尝试其他分类或搜索关键词</p>
          <button 
            @click="selectedCategory = 'all'; searchQuery = ''"
            class="px-10 py-5 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl font-medium hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105 shadow-lg text-xl"
          >
            查看全部资源
          </button>
        </div>
      </div>
      </section>
      <!-- 移除主要内容区右侧 aside -->
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ResourceAPI, type Resource } from '@/api/resource'
import { EbookAPI, type Ebook } from '@/api/ebook'
import { projectApi } from '@/api/project'
import { courseApi, type Course } from '@/api/course'
import BarrageSystem from '@/components/Common/BarrageSystem.vue'

const router = useRouter()

// 响应式数据
const selectedCategory = ref('all')
const searchQuery = ref('')
const selectedDifficulty = ref('')
const selectedSort = ref('latest')
// 自定义下拉组件状态与选项
const difficultyOpen = ref(false)
const sortOpen = ref(false)
const difficultyOptions = [
  { value: '', label: '所有难度' },
  { value: 'beginner', label: '入门' },
  { value: 'medium', label: '进阶' },
  { value: 'advanced', label: '专业' }
]
const sortOptions = [
  { value: 'latest', label: '最新' },
  { value: 'popular', label: '最受欢迎' },
  { value: 'rating', label: '评分最高' }
]
const difficultyLabel = computed(() => difficultyOptions.find(o => o.value === selectedDifficulty.value)?.label || '所有难度')
const sortLabel = computed(() => sortOptions.find(o => o.value === selectedSort.value)?.label || '最新')
const loading = ref(false)
const error = ref('')

// 资源数据
const resources = ref<Resource[]>([])
const ebooks = ref<Ebook[]>([])
const projects = ref<any[]>([])
const courses = ref<Course[]>([])

// 弹幕数据
const resourceBarrageData = [
  // 资源类型标签
  { type: 'tag' as const, text: '电子书', tag: 'book' },
  { type: 'tag' as const, text: '项目', tag: 'project' },
  { type: 'tag' as const, text: '课程', tag: 'course' },
  { type: 'tag' as const, text: '算法', tag: 'algorithm' },
  { type: 'tag' as const, text: '前端', tag: 'frontend' },
  { type: 'tag' as const, text: '后端', tag: 'backend' },
  { type: 'tag' as const, text: '数据库', tag: 'database' },
  { type: 'tag' as const, text: '机器学习', tag: 'ml' },
  { type: 'tag' as const, text: '人工智能', tag: 'ai' },
  { type: 'tag' as const, text: '区块链', tag: 'blockchain' },
  { type: 'tag' as const, text: '云计算', tag: 'cloud' },
  { type: 'tag' as const, text: '移动开发', tag: 'mobile' },
  { type: 'tag' as const, text: '游戏开发', tag: 'game' },
  { type: 'tag' as const, text: '网络安全', tag: 'security' },
  { type: 'tag' as const, text: 'DevOps', tag: 'devops' }
]

// 分类定义 - 只保留三个类型
const categories = [
  { id: 'all', name: '全部' },
  { id: 'book', name: '电子书' },
  { id: 'project', name: '项目' },
  { id: 'course', name: '课程' }
]

// 派生数据 - 合并所有资源（不筛选）
const allResourcesMerged = computed(() => {
  const list: any[] = []
  // 电子书
  ebooks.value.forEach(ebook => {
    list.push({
      id: `book_${ebook.id}`,
      title: ebook.title,
      description: ebook.description,
      author: ebook.author,
      type: 'book',
      category: ebook.category,
      difficulty: 'beginner',
      views: ebook.views,
      likes: ebook.likes,
      thumbnail_url: ebook.cover_image,
      pages: ebook.pages,
      format: ebook.format,
      file_url: ebook.file_url,
      created_at: ebook.created_at,
      is_favorited: false
    })
  })
  // 项目
  projects.value.forEach(project => {
    list.push({
      id: `project_${project.id}`,
      title: project.title,
      description: project.description,
      author: project.author?.username || '未知',
      type: 'project',
      category: project.type,
      difficulty: project.difficulty,
      views: project.view_count,
      likes: project.like_count,
      thumbnail_url: project.cover_image,
      tech_stack: project.tech_stack,
      github_url: project.github_url,
      demo_url: project.demo_url,
      created_at: project.created_at,
      is_favorited: false
    })
  })
  // 课程
  courses.value.forEach(course => {
    list.push({
      id: `course_${course.id}`,
      title: course.title,
      description: course.description,
      author: course.instructor,
      type: 'course',
      category: course.category,
      difficulty: course.difficulty,
      views: course.view_count,
      likes: course.like_count,
      thumbnail_url: course.thumbnail_url,
      video_url: course.video_url,
      duration: course.duration,
      rating: course.rating,
      rating_count: course.rating_count,
      created_at: course.created_at,
      is_favorited: course.is_favorited,
      is_enrolled: course.is_enrolled
    })
  })
  return list
})

// 左右侧栏用的统计与榜单派生
const totalCount = computed(() => allResourcesMerged.value.length)
const todayNewCount = computed(() => allResourcesMerged.value.filter(r => isToday(r.created_at)).length)
const favoritesCount = computed(() => allResourcesMerged.value.filter(r => r.is_favorited).length)

const trendingList = computed(() => allResourcesMerged.value
  .slice()
  .sort((a, b) => (b.views || 0) - (a.views || 0))
  .slice(0, 5)
)

const editorsPickList = computed(() => allResourcesMerged.value
  .slice()
  .sort((a, b) => (b.rating || 0) - (a.rating || 0))
  .slice(0, 5)
)

function isToday(dateStr: string) {
  if (!dateStr) return false
  const d = new Date(dateStr)
  const now = new Date()
  return d.toDateString() === now.toDateString()
}

// 计算属性 - 合并所有资源并应用筛选
const filteredResources = computed(() => {
  let allResources: any[] = []

  // 添加电子书
  ebooks.value.forEach(ebook => {
    allResources.push({
      id: `book_${ebook.id}`,
      title: ebook.title,
      description: ebook.description,
      author: ebook.author,
      type: 'book',
      category: ebook.category,
      difficulty: 'beginner', // 电子书默认难度
      views: ebook.views,
      likes: ebook.likes,
      thumbnail_url: ebook.cover_image,
      pages: ebook.pages,
      format: ebook.format,
      file_url: ebook.file_url,
      created_at: ebook.created_at,
      is_favorited: false // 需要从API获取
    })
  })

  // 添加项目
  projects.value.forEach(project => {
    allResources.push({
      id: `project_${project.id}`,
      title: project.title,
      description: project.description,
      author: project.author?.username || '未知',
      type: 'project',
      category: project.type,
      difficulty: project.difficulty,
      views: project.view_count,
      likes: project.like_count,
      thumbnail_url: project.cover_image,
      tech_stack: project.tech_stack,
      github_url: project.github_url,
      demo_url: project.demo_url,
      created_at: project.created_at,
      is_favorited: false // 需要从API获取
    })
  })

  // 添加课程
  courses.value.forEach(course => {
    allResources.push({
      id: `course_${course.id}`,
      title: course.title,
      description: course.description,
      author: course.instructor,
      type: 'course',
      category: course.category,
      difficulty: course.difficulty,
      views: course.view_count,
      likes: course.like_count,
      thumbnail_url: course.thumbnail_url,
      video_url: course.video_url,
      duration: course.duration,
      rating: course.rating,
      rating_count: course.rating_count,
      created_at: course.created_at,
      is_favorited: course.is_favorited,
      is_enrolled: course.is_enrolled
    })
  })

  // 筛选逻辑
  let filtered = allResources

  // 分类筛选
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(r => r.type === selectedCategory.value)
  }

  // 难度筛选
  if (selectedDifficulty.value) {
    filtered = filtered.filter(r => r.difficulty === selectedDifficulty.value)
  }

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(r =>
      r.title.toLowerCase().includes(query) ||
      r.description.toLowerCase().includes(query) ||
      r.author.toLowerCase().includes(query)
    )
  }

  // 排序
  switch (selectedSort.value) {
    case 'popular':
      filtered = filtered.sort((a, b) => b.views - a.views)
      break
    case 'rating':
      filtered = filtered.sort((a, b) => (b.rating || 0) - (a.rating || 0))
      break
    case 'latest':
    default:
      filtered = filtered.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
      break
  }

  return filtered
})

// 方法
const loadResources = async () => {
  try {
    loading.value = true
    error.value = ''

    // 并行加载所有资源
    const [ebooksRes, projectsRes, coursesRes] = await Promise.all([
      EbookAPI.getEbooks({ page: 1, page_size: 50 }),
      projectApi.getProjects({ page: 1, page_size: 50 }),
      courseApi.getCourses({ page: 1, page_size: 50 })
    ])

    ebooks.value = ebooksRes.items || []
    projects.value = projectsRes.data?.items || []
    courses.value = coursesRes.items || []
  } catch (err: any) {
    error.value = err.message || '加载资源失败'
    console.error('加载资源失败:', err)
  } finally {
    loading.value = false
  }
}

const getResourceTypeName = (type: string): string => {
  const typeMap: { [key: string]: string } = {
    book: '电子书',
    project: '项目',
    course: '课程'
  }
  return typeMap[type] || type
}

const getDifficultyName = (difficulty: string): string => {
  const difficultyMap: { [key: string]: string } = {
    beginner: '入门',
    medium: '进阶',
    advanced: '专业'
  }
  return difficultyMap[difficulty] || difficulty
}

const formatDuration = (minutes: number): string => {
  if (minutes < 60) {
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
  }
}

const viewResource = (resource: any) => {
  const [type, id] = resource.id.split('_')
  
  switch (type) {
    case 'book':
      router.push(`/ebooks/${id}`)
      break
    case 'project':
      router.push(`/projects/${id}`)
      break
    case 'course':
      router.push(`/courses/${id}`)
      break
    default:
      console.log('未知资源类型:', type)
  }
}

const toggleFavorite = async (resource: any) => {
  try {
    const [type, id] = resource.id.split('_')
    
    switch (type) {
      case 'book':
        await EbookAPI.likeEbook(parseInt(id))
        break
      case 'project':
        await projectApi.likeProject(parseInt(id))
        break
      case 'course':
        await courseApi.toggleCourseFavorite(parseInt(id))
        break
    }
    
    // 更新本地状态
    resource.is_favorited = !resource.is_favorited
    resource.likes += resource.is_favorited ? 1 : -1
  } catch (err: any) {
    console.error('收藏操作失败:', err)
    alert(err.message || '操作失败')
  }
}

const enrollCourse = async (resource: any) => {
  try {
    const [, id] = resource.id.split('_')
    await courseApi.enrollCourse({ course_id: parseInt(id) })
    resource.is_enrolled = true
    alert('报名成功！')
  } catch (err: any) {
    console.error('报名失败:', err)
    alert(err.message || '报名失败')
  }
}

const downloadBook = async (resource: any) => {
  try {
    const [, id] = resource.id.split('_')
    const downloadInfo = await EbookAPI.downloadEbook(parseInt(id))
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = downloadInfo.download_url
    link.download = downloadInfo.file_name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (err: any) {
    console.error('下载失败:', err)
    alert(err.message || '下载失败')
  }
}

// 处理弹幕标签点击
const handleTagClick = (tag: string) => {
  // 根据标签设置分类筛选
  switch (tag) {
    case 'book':
    case 'project':
    case 'course':
      selectedCategory.value = tag
      break
    case 'algorithm':
    case 'frontend':
    case 'backend':
    case 'database':
    case 'ml':
    case 'ai':
    case 'blockchain':
    case 'cloud':
    case 'mobile':
    case 'game':
    case 'security':
    case 'devops':
      // 这些标签可以用于搜索
      searchQuery.value = tag
      break
    default:
      console.log('未知标签:', tag)
  }
}

// 导航到资源提交页面
const navigateToSubmitResource = () => {
  router.push('/submit-resource')
}

onMounted(() => {
  loadResources()
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

<style scoped>
.resource-select option { background-color: #ffffff; }
.resource-select option:checked,
.resource-select option:focus,
.resource-select option:active { background-color: #ffffff; color: inherit; }
.resource-select option:hover { background-color: #3b82f6; color: #ffffff; }
</style>